﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NHibernate;
using NHibernate.Context;
using NHibernate.Cfg;
using System.Configuration;
using System.Reflection;

namespace SaladBar.Service.Repositories.NHibernateRepository.SessionManagers
{
    public class SessionPerRequestSessionManager : ISessionManager, IHttpModule
    {
        private static ISessionFactory _sessionFactory;
        private ISession _currentSession;

        public SessionPerRequestSessionManager(NHibernate.Cfg.Configuration cfg)
        {
            if (_sessionFactory == null)
            {
                cfg.EventListeners.PreUpdateEventListeners = new NHibernate.Event.IPreUpdateEventListener[] { new PersistentObjectEventListener() };
                cfg.EventListeners.PreInsertEventListeners = new NHibernate.Event.IPreInsertEventListener[] { new PersistentObjectEventListener() };

                _sessionFactory = cfg.BuildSessionFactory();
            }
        }

        public NHibernate.ISession GetCurrentSession()
        {
            if (this._currentSession == null)
                this._currentSession = _sessionFactory.OpenSession();
            return this._currentSession;
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest; 
        }

        public void Dispose() { }

        private static void BeginRequest(object sender, EventArgs e)
        {
            ISession session = _sessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        }

        private static void EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(_sessionFactory);

            if (session == null) return;

            session.Close();
            session.Dispose();
        }
    }
}
